/*****************************************************************************
 * Copyright (C) Stacy Curl. All rights reserved.                            *
 * ------------------------------------------------------------------------- *
 * The software in this package is published under the terms of the BSD      *
 * style license a copy of which has been included with this distribution in *
 * the LICENSE.txt file.                                                     *
 *****************************************************************************/
package picounit.features.test_finder;

import picounit.features.failures_first.ProblemTracker;

import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import junit.framework.Test;
import junit.framework.TestSuite;

class SortedTestSuite extends TestSuite {
	private final List<SinglePicoUnitTestSuite> tests = new LinkedList<SinglePicoUnitTestSuite>();
	private boolean pushedDown = false;
	private final ProblemTracker problemTracker;

	public SortedTestSuite(String name, ProblemTracker problemTracker) {
		super(name);

		this.problemTracker = problemTracker;
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// TestSuite methods
	///////////////////////////////////////////////////////////////////////////////////////////////
	
	@Override
	public void addTest(Test test) {
		if (pushedDown) {
			super.addTest(test);
		}
		else {
			tests.add((SinglePicoUnitTestSuite) test);
		}
	}
	
	@Override
	public int testCount() {
		if (!pushedDown) {
			pushTestsDown();
		}

		return super.testCount();
	}
	
	@Override
	public Test testAt(int index) {
		if (!pushedDown) {
			pushTestsDown();
		}

		return super.testAt(index);
	}

	@Override
	public Enumeration tests() {
		if (!pushedDown) {
			pushTestsDown();
		}

		return super.tests();
	}

	///////////////////////////////////////////////////////////////////////////////////////////////
	// Implementation methods
	///////////////////////////////////////////////////////////////////////////////////////////////

	private void pushTestsDown() {
		Collections.sort(tests, new Comparator<SinglePicoUnitTestSuite>() {
			public int compare(SinglePicoUnitTestSuite o1, SinglePicoUnitTestSuite o2) {
				return problemTracker.compare(o1.getClass(), o2.getClass());
			}
		});

		for (Object test : tests) {
			super.addTest((Test) test);
		}

		tests.clear();

		pushedDown = true;
	}
}
